package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public String getOpenid(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        HttpResponse response = HttpUtil.createRequest(Method.GET, OPENID_URL)
                .form(paramMap)
                .execute();
        if (response.isOk()) {
            String body = response.body();
            JSONObject entries = JSONUtil.parseObj(body);
            return entries.getStr("openid");
        }
        return null;
    }

    @Override
    public String getPhone(String phoneCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);


        HttpResponse response = HttpUtil.createRequest(Method.POST, PHONE_URL + getToken())
                .body(JSONUtil.toJsonStr(params))
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String phoneNumber = jsonObject.getByPath("phone_info.phoneNumber", String.class);

            return phoneNumber;
        }
        return null;
    }


    private String getToken() {  //为了获取手机号

        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("grant_type", "client_credential");


        HttpResponse response = HttpUtil.createRequest(Method.GET, TOKEN_URL)
                .form(params)
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject.getStr("access_token");
        }
        return null;

    }
}